/**
 * designed by yy(github.com/guaidashu)
 **/
// 奥地利h3g

const puppeteer = require("puppeteer");
const moment = require("moment");

const { createMobile, config } = require("../../../common/mobile");
const {
  info,
  saveFile,
  logging,
  timeout,
  reporter
} = require("../../../common/util");

const name = "h3g";
const today = moment().format("YYYY-MM-DD");
const logdir = `./logs/${today}/au/h3g/${info.deviceid}`;

const r = reporter(name);
const logger = logging(name, logdir);

(async () => {
  const browser = await puppeteer.launch(config);
  const page = await browser.newPage();

  const m = await createMobile(page);

  //sub status linstener
  m._page.on("response", response => {
    let url = response.url();
    let status = response.status();

    if (url.startsWith("http")) {
      logger.info(`${response.request().method()}`, status, url);
    }

    // 订阅成功发送
    if (
      url.startsWith("https://services.dimoco.at/dcb/") &&
      url.endsWith("/ok")
    ) {
      r.s("success");
    }

    if (url.startsWith("http://google.com")) {
      r.w("failure", url);
      m.close();
    }
  });

  //开始
  try {
    r.i("start");

    logger.info("start");

    await m.get(`http://offer.lpaosub.com/offer/track?of=1009`);
    // await m.get(`http://offer.lpaosub.com/offer/track?of=1010`);

    //等待页面加载完成
    await m._page.waitForSelector("#agree", { timeout });
    await m._page.waitForSelector("#submit_btn_mobile", { timeout });

    //保存页面
    saveFile(`${logdir}/1.html`, await m._page.content());

    //勾选
    await m.evaluate(() => {
      document.getElementById("agree").click();
    });

    r.i("sub_click");

    logger.info("click");

    await m.sleep(1000);

    // 点击订阅按钮
    await m.tapElement("button[id='submit_btn_mobile']");

    //等待测试
    logger.info("click2");

    // await m._page.waitForNavigation({ timeout });

    //  await m._page.waitForSelector("input[id='vasb-agb-input']", {timeout});
    // await m._page.waitForSelector("input[id='vasb-fagg-input']", {timeout});
    //await m._page.waitForSelector(
    //  "button[class='button confirm button-A1-confirm']",
    //{timeout}
    //);
    await m._page.waitForSelector("#pin", { timeout });
    await m._page.waitForSelector("input[class='bold green_button']", {
      timeout
    });

    // await m.evaluate(() => {
    //     document.getElementById("vasb-agb-input").click();
    // });

    // await m.evaluate(() => {
    //    document.getElementById("vasb-fagg-input").click();
    //});

    await m.sleep(100);

    async function parseSms(text) {
      logger.info(text);

      // let code = text.substr(30, 4);
      let code = null;

      let pattern = /TAN: /g;

      // 匹配
      let matchResult = text.match(pattern);

      if (matchResult) {
        code = text.substr(5, 4);
      } else {
        console.log("error message", text);
        await m.sms(parseSms);
        return;
      }

      if (code && code.length === 4 && Number(code)) {
        //填入文本
        await m._page.type("#pin", code);

        logger.info("填短信完成");
        await m.sleep(1000 * 3);
      } else {
        console.log("error message", text);
        await m.sms(parseSms);
      }
    }

    // 开始填短信
    logger.info("开始填短信");
    await m.sms(parseSms);

    // 订阅
    await m.tapElement("input[class='bold green_button']");

    logger.info("submit");

    await m._page.waitForNavigation({ timeout });

    saveFile(`${logdir}/2.html`, await m._page.content());

    logger.info("end");

    r.i("end");
  } catch (e) {
    saveFile(`${logdir}/error.html`, await m._page.content());
    r.e(e + "");

    logger.error(e);
  } finally {
    await m.close();
  }
  await browser.close();
})();
